<template>
    <div>
      <h2 style="text-align: left;">更新物资信息</h2>
      <el-row>
        <el-col :span="16" :offset="4">
            <el-form ref="form" :model="goods" label-width="100px" :rules="rules">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="物资名称" prop="goodsName">
                            <el-input v-model="goods.goodsName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库数量" prop="goodsNum">
                            <el-input v-model.number="goods.goodsNum"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="入库仓库" prop="warehouseId">
                            <el-select v-model="goods.warehouseId" placeholder="请选择入库仓库" style="width: 100%">
                                <el-option v-for="item in warehouses" :label="item.warehouseName" :value="item.warehouseId" :key="item.warehouseId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库日期" prop="storeTime">
                            <el-date-picker 
                            type="date" 
                            placeholder="选择日期" 
                            v-model="goods.storeTime" 
                            style="width: 100%"
                            format="yyyy-MM-dd" 
                            value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="物资照片" prop="goodsPicture">
                            <el-upload
                            class="upload"
                            action="#"
                            list-type="picture-card"
                            :show-file-list="false"
                            :before-upload="beforeUpload"
                            :http-request="handleUpload"
                            :on-success="handleSuccess"
                            :on-remove="handleRemove"
                            :disabled="isBoundToTravel"
                            >

                            <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 150px; height: 150px; object-fit: cover;">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">确定</el-button>
                            <el-button @click="onCancel">取消</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-col>
      </el-row>
      
    </div>
</template>

<script>
export default {
    name: 'AddorEditGoods',
    data(){
        return{
            
            goods:{
                goodsId:0,
                goodsName:'',
                goodsNum:"",
                warehouseId:"",
                storeTime:"",
                goodsPicture:''
            },
            imageUrl:'',
            goodsLog:{
                logId:0,
                goodsId:0,
                goodsNum:0,
                goodsChangeType:'',
                goodsChangeTime:'',
                goodsChangeReason:'',
                loggedEmpNo:0,
                loggedEName:'',
                goodsName:'',
            },
            
            warehouses:[],
            empno:0,
            ename:"",
            originNum:0,
            rules:{
                goodsName:[
                    {required:true,message:'请输入商品名称',trigger:'blur'}
                ],
                goodsNum:[
                    {required:true,message:'请输入商品数量',trigger:'blur'}
                ],
                warehouseId:[
                    {required:true,message:'请选择仓库',trigger:'change'}

                ],
                storeTime:[
                    {required:true,message:'请选择入库时间',trigger:'change'}
                ],
                goodsPicture:[
                    {required:true,message:'请上传商品图片',trigger:'blur'}
                ],
            }
        }
    },
    watch:{
        "goods.goodsNum":{
                handler(newVal,oldVal){
                    // console.log(newVal)
                    // console.log(oldVal)
                    if (newVal != this.originNum){
                        this.goodsLog.goodsNum = newVal - this.originNum
                    } else {
                        this.goodsLog.goodsNum = 0
                    }
                }
            },
    },
    methods:{
        getWarehouse(){ 
            this.$http.get("/lc/queryWarehouseByEmpNo?empNo="+this.empno).then(res => {
                this.warehouses = res.data;
            }).catch(err => {
              console.error("Error getting warehouses:", err);
              this.$message.error("获取仓库信息失败: " + err.message);
            })
        },
        onCancel(){ 
            if (this.goods.goodsId == 0 ){
                if (this.goods.goodsPicture) { // 检查是否有旧图片URL
                    try {
                    // 调用后端删除图片接口（需后端配合实现）
                    this.$http.post('/deleteGoodsImage', { 
                        imageUrl: this.goods.goodsPicture // 传入旧图片的URL
                    }).catch(err => {
                      console.error("Error deleting goods image:", err);
                    });
                    // console.log('旧图片删除成功');
                    } catch (err) {
                    }
                }
            }
            this.$router.push({
                path: '/goodsManager'
            })
        },
        onSubmit(){
            //表单验证
            this.$refs['form'].validate((valid) => { 
                if (valid) { 
                    if(this.goods.goodsId == 0){
                        this.goodsLog.goodsChangeReason = "新增物资";
                        this.goodsLog.goodsChangeTime = this.goods.storeTime;
                        this.goodsLog.goodsNum = this.goods.goodsNum;
                        this.goodsLog.goodsChangeType = "入库";
                        this.goodsLog.goodsId = this.goods.goodsId;
                        this.goodsLog.goodsName = this.goods.goodsName;
                        this.goodsLog.loggedEmpNo = this.empno
                        this.goodsLog.loggedEName = this.ename
                        let form = {
                            goods: this.goods,
                            goodsLog: this.goodsLog
                        }
                        this.$http.post("/lc/addGoods",form).then(res => { 
                            if (res.data == "success"){
                                
                                this.$router.push({
                                    path: '/goodsManager',
                                    query: { 
                                        msg: '添加成功'
                                    }
                                })
                            } else {
                                this.$message.error('添加失败'); 
                            }
                        }).catch(err => {
                        console.error("Error adding goods:", err);
                        this.$message.error("添加物资失败: " + err.message);
                        })
                    } else { 
                        this.goodsLog.goodsChangeReason = "物资变动";
                        this.goodsLog.goodsChangeTime = this.goods.storeTime;
                        
                        this.goodsLog.goodsChangeType = "更新";
                        this.goodsLog.goodsId = this.goods.goodsId;
                        this.goodsLog.goodsName = this.goods.goodsName;
                        this.goodsLog.loggedEmpNo = this.empno
                        this.goodsLog.loggedEName = this.ename
                        let form = {
                            goods: this.goods,
                            goodsLog: this.goodsLog
                        }
                        this.$http.post("/lc/updateGoods",form).then(res => { 
                            if(res.data == "success"){
                                this.$router.push({
                                    path: '/goodsManager',
                                    query:{
                                        msg:"修改成功！"
                                    }
                                })
                            } else {
                                this.$message.error('修改失败！')
                            }
                        }).catch(err => {
                        console.error("Error updating goods:", err);
                        this.$message.error("更新物资失败: " + err.message);
                        })
                    }
                } else {
                    this.$message.error('请填写必填项！');
                }
            });
            
        },
    beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG || isPNG && isLt2M;
    },
        // 自定义上传方法（核心）
    async handleUpload(config) {
        // config 包含上传的文件信息：config.file 是选中的文件
        const file = config.file;

        // 第一步：如果存在旧图片，先删除旧图片
        if (this.goods.goodsPicture) { // 检查是否有旧图片URL
            try {
            // 调用后端删除图片接口（需后端配合实现）
            await this.$http.post('/deleteGoodsImage', { 
                imageUrl: this.goods.goodsPicture // 传入旧图片的URL
            }).catch(err => {
              console.error("Error deleting goods image:", err);
              this.$message.error("删除旧图片失败: " + err.message);
            });
            // console.log('旧图片删除成功');
            } catch (err) {
            // console.error('删除旧图片失败：', err);
            // 可选：删除旧图失败时，仍可继续上传新图（避免阻塞流程）
            this.$message.warning('旧图片删除失败，但将继续上传新图片');
            }
        }
            
            // 构建FormData（文件上传必须用multipart/form-data格式）
            const formData = new FormData();
            formData.append('file', file); // 后端接口用@RequestParam("file")接收
            
            // 调用后端接口
            this.$http.post('/addPicture', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'  // 显式指定内容类型
            }
            }).then(res => {
            // 上传成功：调用el-upload的成功回调，更新组件状态
            if (res.data.code === 200) {
                this.goods.goodsPicture = res.data.data; // 存储后端返回的图片URL
                config.onSuccess(res.data); // 通知组件上传成功
                this.$message.success('图片上传成功');
            } else {
                config.onError(res.data); // 通知组件上传失败
                this.$message.error('图片上传失败：' + res.data.msg);
            }
            }).catch(err => {
            // 网络错误处理
            // config.onError(err);
            this.$message.error('上传失败：网络错误');
            console.error('上传错误：', err);
            });
    },
    // 新增：删除图片时清空表单中的图片路径
        handleRemove(file, fileList) {
            if (fileList.length === 0) {
            this.goods.goodsPicture = ''; // 最后一张图片被删除，清空路径
            this.imageUrl = ''; 
            }
        },
        handleSuccess(res, file) {
        this.imageUrl = this.goods.goodsPicture;
        }
    },
    mounted(){
        // //获取当前日期
        // var date = new Date();
        // this.form.goods.storeTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
        this.empno = localStorage.getItem('empno')
        this.ename = localStorage.getItem('ename')
        this.getWarehouse()
        if (this.$route.query.goods != null){
            this.goods = this.$route.query.goods
            this.originNum = this.$route.query.goods.goodsNum
            this.imageUrl = this.$route.query.goods.goodsPicture
            this.goods.goodsPicture = this.$route.query.goods.goodsPicture
        }
        
    }

}
</script>

<style >

</style>